//
//  MTTimer.swift
//  MTCategory
//
//  Created by M on 2019/12/24.
//  Copyright © 2019 张强. All rights reserved.
//

import Foundation

public class MTTimer {
    
    /// 单例
    public static let `default`: MTTimer = MTTimer()
    
    /// 容器
    private lazy var container: [String: DispatchSourceTimer] = [String: DispatchSourceTimer]()
    
    /// 执行一个计时器
    public func scheduledTimer(withName name: String, timeInterval: TimeInterval, queue: DispatchQueue, repeats: Bool, action: @escaping ()->()) {
        var timer = container[name]
        if timer == nil {
            timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
            timer?.resume()
            container[name] = timer
        }
        
        timer?.schedule(deadline: .now(), repeating: timeInterval, leeway: DispatchTimeInterval.milliseconds(100))
        timer?.setEventHandler(handler: { [weak self] in
            action()
            if repeats == false {
                self?.removeTimer(name: name)
            }
        })
        
    }
    
    /**
     移除计时器
     
     @param         name: 计时器名字
     */
    public func removeTimer(name: String) {
        if let timer = container[name] {
            container.removeValue(forKey: name)
            timer.cancel()
        }
    }
    
    /// 计时器是否存在
    public func isTimerExisted(name: String) -> Bool {
        return container[name] != nil
    }
    
}
